package com.fastmobile.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.fastmobile.dao.UserDAO;
import com.fastmobile.entity.User;
import com.fastmobile.util.Util;

public class UserImpl implements UserDAO{
	
	@PersistenceContext(unitName = "com.fastmobile")
	protected EntityManager em;

	public EntityManager getEntityManager() {
		return em;
	}

	public User addOrUpdate(User user) {
		User obj = null;
		if (!Util.isNullOrBlank(user.getId())) {
			obj = find(user.getId());
		}
		if (null == obj) {
			getEntityManager().persist(user);
		} else {
			obj.copy(user);
		}
		return user;
	}

	public void remove(Long id) {
		User user = find(id);
		if (null != user) {
			getEntityManager().remove(user);
		}
	}

	public User find(Long id) {
		return getEntityManager().find(User.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<User> findAll() {
		Query query = em.createNamedQuery("user.findAll");
		List<User> results = query.getResultList();
		if (null != results) {
			return results;
		}
		return null;
	}
	
	
}
